package cn.lzd.mvp.base.net;

import cn.lzd.mvp.base.net.log.RequestInterceptor;
import com.blankj.utilcode.util.GsonUtils;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class NetManager {
    private static NetManager netManager;
    Retrofit retrofit;

    private static final Map<String, String> headerMap = new HashMap<>();

    private NetManager() {
        // 我们使用的是Retrofit代管网络，这是他的初始化方法
        retrofit = new Retrofit.Builder()
                .client(obtainOKHttpClient())
                // 这是基础url,会跟 Service 中的 拼接
                .baseUrl("https://www.7timer.info")
                .addConverterFactory(GsonConverterFactory.create(GsonUtils.getGson()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        headerMap.put("aa", "bb");
    }

    private OkHttpClient obtainOKHttpClient() {
        return new OkHttpClient.Builder()
                .callTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new RequestInterceptor(RequestInterceptor.Level.ALL, headerMap))
                .build();
    }

    public static NetManager getInstance() {
        if (netManager == null) {
            throw new RuntimeException("你还没有初始化 NetManager");
        }
        return netManager;
    }

    // 这两个操作，保证唯一，放到Application中
    // 初始化，单例模式，保证唯一
    public static void init() {
        netManager = new NetManager();
    }

    // 释放资源
    public static void release() {
        if (netManager != null) {
            netManager.retrofit = null;
            netManager = null;
        }
    }

    public <T> T bindService(Class<T> targetInterface) {
        return retrofit.create(targetInterface);
    }
}
